package api.login;

import bean.User;
import db.UserMockTable;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String name=request.getParameter("yhm");
        String pwd=request.getParameter("mima");
        HttpSession session=request.getSession();

        User user=UserMockTable.getUserByName(name);
        String msg;
        response.setContentType("text/html;charset=utf-8");
        if(user==null){
            msg="该用户不存在，登录失败！三秒后自动跳转到登录页面！";
            response.getWriter().write(msg);
            response.setHeader("Refresh","3;URL=/login.html");
        }else if(user.getPassword().equals(pwd)){
            msg="登录成功！";//登录成功后，要为该浏览器在服务器端生成一个session，用来记录后面的访问读写数据
            session.setAttribute("user",user);
            Cookie cookie=new Cookie("JSESSIONID",session.getId());
            response.addCookie(cookie);
            response.getWriter().write(msg);
            response.getWriter().write("<a href='/cart'>点击我，就选购两件商品,进入了购物车页面</a><br/>");
            response.getWriter().write("<a href='/logout'>退出登录</a>");
        }else {
            msg="密码不正确，登录失败！三秒后自动跳转到登录页面！";
            response.getWriter().write(msg);
            response.setHeader("Refresh","3;URL=/login.html");
        }

    }
}
